package com.apimarket.service;

import com.apimarket.dao.SysMenuMapper;
import com.apimarket.dao.SysRoleMenuMapper;
import com.apimarket.entity.SysMenu;
import com.apimarket.entity.vo.Node;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.rpc.ServiceException;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public PageInfo<Map<String, Object>> findObjects(Integer page,Integer pageSize) throws ServiceException {
        PageHelper.startPage(page,pageSize);
        List<Map<String, Object>> list =
                sysMenuMapper.findObjects();

        if (list == null || list.size() == 0)
            throw new ServiceException("没有对应的菜单信息");
        PageInfo<Map<String, Object>> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int deleteObject(Integer id) throws ServiceException {
        //1.验证数据的合法性
        if(id==null||id<=0)
            throw new IllegalArgumentException("请先选择");
        //2.基于id进行子元素查询
        int count=sysMenuMapper.getChildCount(id);
        System.out.println("count"+count);
        if(count>0)
            throw new ServiceException("请先删除子菜单");
        //3.删除角色,菜单关系数据
        sysRoleMenuMapper.deleteObjectsByMenuId(id);
        //4.删除菜单元素
        int rows=sysMenuMapper.deleteObject(id);
        if(rows==0)
            throw new ServiceException("此菜单可能已经不存在");
        //5.返回结果
        return rows;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuMapper.findZtreeMenuNodes();
    }

    @Override
    public int saveObject(SysMenu entity) {
        //1.合法验证
        if(entity==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getName()))
            throw new IllegalArgumentException("菜单名不能为空");
        //2.保存数据
        int  rows=sysMenuMapper.insertObject(entity);
        //3.返回数据
        return rows;
    }

    @Override
    public int updateObject(SysMenu entity) throws ServiceException {
        //1.合法验证
        if(entity==null)
            throw new ServiceException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getName()))
            throw new ServiceException("菜单名不能为空");

        //2.更新数据
        int rows=sysMenuMapper.updateObject(entity);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        //3.返回数据
        return rows;
    }


}
